import { SetStateAction, useEffect, useState } from "react"
interface ListItem{
    id: number
    text:string
}
interface PropsItem{
    title:string
}
 function fetchTitle(title:string) {
        const delay:number = title=== '迈阿密热火' ? 2000 : 200
        return new Promise<ListItem[]>((resolve) => {
            setTimeout(() => {
            resolve([
                { id: 1, text: title + 1 },
                { id: 2, text: title + 2 },
                { id: 3, text: title + 3 }
            ])
            },delay)
        })
}
    
export default function App() {
    const [show, setShow] = useState(true)
    const [title, setTitle] = useState('迈阿密热火')
    const handleClick = () => {
        setShow(!show)
    }
    const handleChange = (e: { target: { value: SetStateAction<string> } }) => {
        setTitle(e.target.value)
    }
    return (
        <>
            <h1>UseEffcet</h1>
            <h2 onClick={handleClick}>{show ? '关闭聊天室' : '开启聊天室'}</h2>
            <select value={title} onChange={handleChange}>
                <option value="迈阿密热火">迈阿密热火</option>
                <option value="利雅得胜利">利雅得胜利</option>
            </select>
            {show && <Chat title={title}></Chat>}
        </>
    )
}

function Chat({ title }: PropsItem) {
    const [list,setList] = useState<ListItem[]>([])
    useEffect(() => {
        let ignore = false
        async function fetch() {
        const data = await fetchTitle(title)
            if (!ignore) {
              setList(data)  
            }
        }
        fetch()
        return () => {
            ignore = true
        }
    }, [title])

    useEffect(() => {
        console.log('进入聊天室',title);
        return () => {
            console.log('退出聊天室', title);
    }
    },[title])
    
    return (
        <>
            <h2>Open Chat</h2>
            {list.map(item => <li key={item.id}>{ item.text}</li>)}
        </>
    )
}